package hauwei.year2024.tools;

public class UnionFind {

    int[] fa; //祖先节点

    public UnionFind(int n) {
        fa = new int[n + 1]; // 初始化父节点数组
        for (int i = 0; i <= n; i++) {
            fa[i] = i;
        }
    }

    public int find(int x) {
        if (fa[x] != x) {
            fa[x] = find(fa[x]); // 路径压缩
        }
        return fa[x];
    }

    public void union(int x, int y) {
        int fax = find(x);
        int fay = find(y);
        if (fax != fay) {
            fa[fax] = fay; // 合并集合
        }
    }

    public static void main(String[] args) {
        UnionFind uf = new UnionFind(5);
    }
}
